﻿using UnityEngine;
using System.Collections;

public class MenueAni : MonoBehaviour {

	private enum AnimType
	{
		Position,
		Colour
	}

	private AnimType type;
	private Vector3 startPos;
	private Vector3 endPos;
	private Color startCol;
	private Color endCol;
	private float time = 1.0f;
	private float delay = 0.0f;
	private float percentage = 0.0f;
	private float prevFrameTime = 0.0f;

	/// <summary>
	/// Moves to.
	/// </summary>
	/// <param name="target">Target.</param>
	/// <param name="pos">Position.</param>
	/// <param name="time">Time.</param>
	/// <param name="delay">Delay.</param>
	public static void MoveTo(GameObject target, Vector3 pos, float time, float delay)
	{
		MenueAni anim = target.AddComponent<MenueAni> ();
		anim.type = AnimType.Position;
		anim.startPos = target.transform.position;
		anim.endPos = pos;
		anim.time = time;
		anim.delay = delay;
	}
	/// <summary>
	/// Initializes the <see cref="MenueAni"/> class.
	/// </summary>
	/// <param name="target">Target.</param>
	/// <param name="col">Col.</param>
	/// <param name="time">Time.</param>
	/// <param name="delay">Delay.</param>
	public static void FadeTo(GameObject target, Color col, float time, float delay)
	{
		MenueAni anim = target.AddComponent<MenueAni> ();
		anim.type = AnimType.Colour;
		anim.startCol = target.GetComponent<Renderer>().material.color;
		anim.endCol = col;
		anim.time = time;
		anim.delay = delay;
	}

	void Start()
	{
		prevFrameTime = Time.realtimeSinceStartup;
	}

	void Update()
	{
		float deltaTime = Time.realtimeSinceStartup - prevFrameTime;
		prevFrameTime = Time.realtimeSinceStartup;
		delay -= deltaTime;
		if (delay > 0.0f)
			return;

		bool complete = false;
		percentage += deltaTime / time;
		if (percentage > 1.0f) 
		{
			percentage = 1.0f;
			complete = true;
		}

		float t = percentage * percentage * percentage;

		switch(type)
		{
		case AnimType.Position:
			transform.position = Vector3.Lerp (startPos, endPos, t);
			break;
		case AnimType.Colour:
			GetComponent<Renderer> ().material.color = Color.Lerp (startCol, endCol, t);
			break; 	
		default:
			break;
		}

		if (complete)
			Destroy (this);
	}
}
